package com.sinping.qh.api.filter;

import com.sinping.qh.api.support.Const;
import com.sinping.qh.api.support.ResDto;
import com.sinping.qh.service.app.auth.ISessionMongoService;
import com.sinping.qh.service.redis.RedisCommon;
import com.sinping.qh.service.redis.RedisService;
import com.sinping.qh.utils.mapper.JsonMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zhangjin
 * @create 2018/6/2
 */
public class AppAuthFilter implements Filter {

    private final static Logger log = LoggerFactory.getLogger(AppAuthFilter.class);
    public static final String token_name = "token";

    private FilterConfig filterConfig;


    @Autowired
    ISessionMongoService iSessionMongoService;

    @Autowired
    RedisService redisService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig=filterConfig;

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        ResDto resDto = new ResDto();
        HttpServletRequest r = (HttpServletRequest) request;
        HttpServletResponse q = (HttpServletResponse) response;
        String token = this.retriveParaFromHeaderOrRquest(request, token_name);
        //传入的token为null或者redis存储基本信息为null
        if(!StringUtils.isNotBlank(token))
        {
            resDto.setStatus(Const.PARAM_ERROR);
            resDto.setMsg("请重新登录");
            this.sendJsonMessage(request, response, resDto);
            return;
        }
        if(!redisService.existsKey(RedisCommon.RedisPrimaryKey.UserSessionByApp.getFirstKey()+token))
        {
            resDto.setStatus(Const.UNAUTHORIZED);
            resDto.setMsg("用户没有登录");
            this.sendJsonMessage(request, response, resDto);
            return;
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        this.filterConfig = null;
    }

    private void sendJsonMessage(ServletRequest request, ServletResponse response, ResDto resDto) {
        try {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            httpServletResponse.setCharacterEncoding("UTF-8");
            httpServletResponse.setContentType("application/json");
            httpServletResponse.getWriter().write(JsonMapper.defaultMapper().toJson(resDto));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String retriveParaFromHeaderOrRquest(ServletRequest request, String param) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String header = httpServletRequest.getHeader(param);
        if (StringUtils.isEmpty(header)) {
            return httpServletRequest.getParameter(param);
        } else {
            return header;
        }
    }
}
